package Utils::WebUtils;

use strict;
use warnings;
use utf8;

use Exporter qw(import);
use JSON -convert_blessed_universally;
use Utils::Constants;

use Mojo::Log;

use Data::UUID;

our @EXPORT = qw/
		convert_to_json 
		get_result_code_json
        json_to_hash
        create_uuid
		/;

my $log = Mojo::Log->new;

sub convert_to_json {
	my $raw_object = shift;
	my $json_obj = JSON->new->allow_blessed->convert_blessed;
	my $json_string = $json_obj->encode($raw_object);

	return $json_string;
}

sub get_result_code_json {
	my $result_code = shift;
	my @res = ();
	my %result = (
		Utils::Constants::RESULT_CODE_NAME =>  $result_code,
	);
	
	push @res, \%result;

	return convert_to_json(\@res);
}

sub extract_filename_from_path {
    my $path = shift;
    my @filename = split('/', $path);
    
    return $filename[-1];
}

sub trim {
    my $s = shift;
    
    return '' unless defined $s;

    $s =~ s/^\s+|\s+$//g;

    return $s;
}

sub is_empty {
    my $raw = shift;
    my $is_empty = 1;

    $is_empty = 0 if defined $raw and trim($raw) ne '';

    return $is_empty;
}

sub json_to_hash {
    return JSON->new->utf8->decode(shift);
}

sub create_uuid {
    my $ug = Data::UUID->new;
    my $uuid = $ug->create_str();
    
    return $uuid;
}

1;

=encoding utf8

=head1 NAME

Utils::WebUtils - Utilities for web development

=head1 SYNOPSIS

  use Utils::WebUtils;
  
  my $json_str = Utils::WebUtils::convert_to_json($an_object_or_a_ref_to_something);

=head1 DESCRIPTION

L<Utils::WebUtils> is a collection of utilities for web development

=head1 METHOD

=head2 convert_to_json

  my $json_str = Utils::WebUtils::convert_to_json($an_object_or_a_ref_to_something);

Convert any object to its JSON representation.

=head1 SEE ALSO

L<JSON>.

=cut
